<template>
  <div class="bk">
    <h1 class="t1">防 反 贫 数 字 化 监 测 平 台</h1>
    <div class="login-container">
      <el-card class="login-card">
        <template #header>
          <h1 style="text-align: center;">登  录</h1>
        </template>

        <el-form
            ref="loginFormRef"
            label-width="70px"
            class="login-form"
            :model="loginForm"
            :rules="rules"
        >
          <!-- 添加 prop 属性使验证生效 -->
          <el-form-item label="用户名" prop="username">
            <el-input
                type="text"
                v-model="loginForm.username"
                placeholder="请输入用户名"
            ></el-input>
          </el-form-item>

          <!-- 添加 prop 属性使验证生效 -->
          <el-form-item label="密 &nbsp&nbsp 码" prop="password">
            <el-input
                type="password"
                v-model="loginForm.password"
                placeholder="请输入密码"
                show-password
            ></el-input>
          </el-form-item>

          <el-form-item label="选择身份" prop="role">
            <el-select
              style="width: 280px;"
              v-model="loginForm.role"
              placeholder="请选择身份"
              padding-left="30px"
            >
              <el-option label="用户" value="user" />
              <el-option label="省级干部" value="provinceCadre" />
              <el-option label="市县干部" value="cityCadre" />
              <el-option label="乡村干部" value="villageCadre" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>
          
          <!-- 验证码 -->
          <el-form-item label="验证码" prop="captcha">
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-input
                  type="text"
                  v-model="loginForm.captcha"
                  placeholder="请输入验证码"
                  style="width: 150px;"
              ></el-input>
              <div class="captcha-code" @click="refreshCaptcha">{{ captchaText }}</div>
            </div>
          </el-form-item>

          <div class="reg-bar" id="reg-bar">
            <a class="reg" href="#" @click.prevent="handleRegister">立即注册</a>
            <a class="forget" href="#" @click.prevent="handlePassword">忘记密码</a>
          </div>
        </el-form>

        <template #footer>
          <div style="text-align: center;" class="ov">
            <el-button 
              type="primary" 
              @click.prevent="submitForm" 
              size="large"
              :loading="loading"
            >
              登录
            </el-button>
            <el-button type="primary" @click.prevent="handleCancel" size="large">取消</el-button>
          </div>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {loginCadreTableAPI ,loginPoorFamilyAPI,loginAdmin} from '@/api/login'
const router = useRouter();
const loginFormRef = ref();
const loading = ref(false);

// 生成随机验证码
const generateCaptcha = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return captcha;
};

const captchaText = ref(generateCaptcha());

// 刷新验证码
const refreshCaptcha = () => {
  captchaText.value = generateCaptcha();
};

// 登录表单数据
let loginForm = reactive({
  username: '',
  password: '',
  role:'',
  captcha: ''
});

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 16, message: '长度在2-16个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在6-16个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码为4位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择身份', trigger: 'change' }
  ],
});

// 登录提交方法 - 添加了表单验证逻辑
const submitForm = async () => {
  try {
    // 1. 验证表单输入是否合法
    const isValid = await validateForm();
    console.log(`role---->`,loginForm.role);
    
    if (!isValid) {
      ElMessage.warning('请填写正确的用户名、密码和验证码');
      return;
    }
    
    // 2. 验证码校验
    if (loginForm.captcha.toUpperCase() !== captchaText.value) {
      ElMessage.warning('验证码错误，请重新输入');
      refreshCaptcha();
      return;
    }
    
    loading.value = true;
    if(loginForm.role=="user"){
      //调用用户的login函数
      loginPoorFamilyAPI(loginForm).then(res=>{
      if(res.code == 2000){
        // 将登录的信息存储
        localStorage.setItem("loginRoleType", loginForm.role);
       localStorage.setItem("login",JSON.stringify(res.data)) 
       // 路由跳转
       router.push("/application")
      }else{
        if(res.message=="用户不存在"){ElMessage.error("用户不存在")}
        else{ElMessage.error("密码错误")}
            }
      }).catch(err=>{});
    }
    else if(loginForm.role=="provinceCadre"||loginForm.role=="cityCadre"||loginForm.role=="villageCadre"){
      loginCadreTableAPI(loginForm).then(res=>{
      if(res.code == 2000){
        // 将登录的信息存储
       localStorage.setItem("loginRoleType", loginForm.role);
       localStorage.setItem("login",JSON.stringify(res.data)) 
       // 路由跳转
       if(loginForm.role=="provinceCadre"){
        router.push("/PClueManagement")
       }
       else if(loginForm.role=="cityCadre"){
        router.push("/ClueProcessing")
       }
       else{
       router.push("/interviewList")}
      }else{
        if(res.message=="用户不存在"){ElMessage.error("用户不存在")}
        else{ElMessage.error("密码错误")}
            }
      }).catch(err=>{});
    }
    else{
      loginAdmin(loginForm).then(res=>{
      if(res.code == 2000){
        // 将登录的信息存储
        localStorage.setItem("loginRoleType", loginForm.role);
       localStorage.setItem("login",JSON.stringify(res.data)) 
       // 路由跳转
       router.push("/CadreManagement")
      }else{
        if(res.message=="用户不存在"){ElMessage.error("用户不存在")}
        else{ElMessage.error("密码错误")}
            }
      }).catch(err=>{});

    } 
  } catch (error) {
    console.error('登录失败:', error);
    ElMessage.error('登录失败，请检查用户名、密码和验证码');
  } finally {
    loading.value = false;
  }
};

// 表单验证方法 - 判断输入是否合法
const validateForm = async () => {
  try {
    await loginFormRef.value.validate();
    return true; // 验证通过
  } catch (error) {
    console.log('表单验证失败:', error);
    return false; // 验证失败
  }
};

// 取消按钮处理
const handleCancel = () => {
  router.go(-1);
};

// 注册处理
const handleRegister = () => {
  router.push('/register');
};

// 忘记密码处理
const handlePassword = () => {
  router.push('/password');
};
</script>

<style lang="less" scoped>
/* 保持原有样式不变 */
.bk {
  background-image: url("../assets/background.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.login-container {
  display: flex;
  justify-content: center;
  margin-top: 80px;
  height: 60vh;
  width: 100%;
}

.login-card {
  align-items: center;
  width: 520px;
  border-radius: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.5);
  text-align: center;
}

.login-form {
  align-items: center;
  padding: 10% 30px;
  .el-form-item {
    margin-bottom: 25px;
    font-size: 300px;
  }
}

#reg-bar {
  display: flex;
  justify-content: center;
  gap: 140px;
  margin-top: 5px;
}

.reg-bar a {
  color: #666;
  font-size: 16px;
  text-decoration: none;
}

.reg-bar a:hover {
  color: #5c67f2;
}
.t1{
  margin-top:90px;
  font-size:60px;
  text-align: center;
}
.ov{
  margin-top: 20px;
}
.login-form .el-input {
  width: 280px;
}

/* 验证码样式 */
.captcha-code {
  width: 100px;
  height: 40px;
  background-color: #f5f5f5;
  color: #333;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  line-height: 40px;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  letter-spacing: 2px;
  position: relative;
  overflow: hidden;
}

.captcha-code::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent 25%, rgba(0,0,0,0.05) 25%, 
    rgba(0,0,0,0.05) 50%, transparent 50%, transparent 75%, rgba(0,0,0,0.05) 75%);
  background-size: 4px 4px;
  z-index: 0;
}

.captcha-code span {
  position: relative;
  z-index: 1;
}

.captcha-code:hover {
  background-color: #e8e8e8;
}

</style>
